package com.bolt.admin.module.sys.repository;


import com.bolt.admin.module.sys.entity.PrivilegeEntity;
import com.bolt.support.spring.jpa.repository.BasicJpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.QueryHints;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import javax.persistence.QueryHint;
import java.util.List;
import java.util.Set;


@Repository
public interface PrivilegeRepository extends BasicJpaRepository<PrivilegeEntity, String> {

    @Query("from PrivilegeEntity order by code asc")
    @QueryHints({@QueryHint(name = org.hibernate.jpa.QueryHints.HINT_CACHEABLE, value = "true")})
    List <PrivilegeEntity> findAllCached();

    Iterable <PrivilegeEntity> findByEnabled(Boolean enabled);

    PrivilegeEntity findByCode(String code);

    @Query(" Select p from PrivilegeEntity p where p.menuId in (:menuIds)")
    List <PrivilegeEntity> findPrivilegeByMenuId(@Param("menuIds") Long[] menuIds);


    @Query(" Select p.id from PrivilegeEntity p where p.menuId in (:menuIds) and p.type=:type")
    List <String> findPrivilegeIdsByMenuId(@Param("menuIds") Long[] menuIds, @Param("type") PrivilegeEntity.PrivilegeTypeEnum type);


    @Query(" Select p.id from PrivilegeEntity p where p.menuId in (:menuIds)")
    List <String> findPrivilegeIdsByMenuId(@Param("menuIds") Long[] menuIds);

    @Query("  from PrivilegeEntity p where p.menuId = :menuId and p.type=:type")
    List <PrivilegeEntity> findPrivileges(@Param("menuId") Long menuId, @Param("type") PrivilegeEntity.PrivilegeTypeEnum type);
    /**
     * 基于角色代码集合查询关联的启用状态的权限集合
     *
     * @param roleId
     * @return
     */
    @Query("select distinct p from PrivilegeEntity p,RoleR2Privilege r2p  "
            + "where p=r2p.privilege   "
            + "and r2p.roleId in (:roleId) and p.enabled=true order by p.code asc")
    List <PrivilegeEntity> findPrivileges(@Param("roleId") Set <String> roleId);


    /**
     * 基于角色ID只查出BUTTON权限资源
     *
     * @param roleId
     * @return
     */
    @Query("select distinct p from PrivilegeEntity p,RoleR2Privilege r2p,RoleEntity r "
            + "where p=r2p.privilege and r2p.role=r  "
            + "and r.id = :roleId and r.enabled=true and p.enabled=true order by p.code asc")
    List <PrivilegeEntity> findPrivileges(@Param("roleId") String roleId);


}
